package com.stx.jeepay.payment.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.stx.jeepay.core.entity.PayOrderEntity;
import com.stx.jeepay.core.enums.CS;
import com.stx.jeepay.core.mq.model.PayOrderDivisionMQ;
import com.stx.jeepay.core.mq.vender.IMQSender;
import com.stx.jeepay.core.service.PayOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 订单处理通用逻辑
 */
@Service
@Slf4j
public class PayOrderProcessService {

    @Autowired
    private PayOrderService payOrderService;

    @Autowired
    private PayMchNotifyService payMchNotifyService;

    @Autowired
    private IMQSender mqSender;

    /**
     * 明确成功的处理逻辑（除更新订单其他业务）
     **/
    public void confirmSuccess(PayOrderEntity payOrder) {
        // 查询查询订单详情
        payOrder = payOrderService.getById(payOrder.getPayOrderId());

        //设置订单状态
        payOrder.setState(PayOrderEntity.STATE_SUCCESS);

        //自动分账 处理逻辑， 不影响主订单任务
        this.updatePayOrderAutoDivision(payOrder);

        //发送商户通知
        payMchNotifyService.payOrderNotify(payOrder);
    }

    /**
     * 更新订单自动分账业务
     **/
    private void updatePayOrderAutoDivision(PayOrderEntity payOrder) {
        try {
            //默认不分账  || 其他非【自动分账】逻辑时， 不处理
            if (payOrder == null || payOrder.getDivisionMode() == null || payOrder.getDivisionMode() != PayOrderEntity.DIVISION_MODE_AUTO) {
                return;
            }

            //更新订单表分账状态为： 等待分账任务处理
            boolean updDivisionState = payOrderService.update(new LambdaUpdateWrapper<PayOrderEntity>()
                    .set(PayOrderEntity::getDivisionState,PayOrderEntity.DIVISION_STATE_WAIT_TASK)
                    .eq(PayOrderEntity::getPayOrderId,payOrder.getPayOrderId())
                    .eq(PayOrderEntity::getDivisionState,PayOrderEntity.DIVISION_STATE_UNHAPPEN));

            if (updDivisionState){
                //推送到分账MQ
                mqSender.send(PayOrderDivisionMQ.build(payOrder.getPayOrderId(), CS.YES,null), 80); //80s 后执行
            }
        } catch (Exception e) {
            log.error("订单[{}]自动分账逻辑异常：", payOrder.getPayOrderId(), e);
        }
    }
}
